package com.xinQing.blogme.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.BasicErrorController;
import org.springframework.boot.autoconfigure.web.DefaultErrorAttributes;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义全局异常Controller
 *
 * Created by null on 2017/4/5.
 */
@Slf4j
@Controller
public class MyErrorController extends BasicErrorController {

    @Autowired
    public MyErrorController(ServerProperties serverProperties) {
        super(new DefaultErrorAttributes(), serverProperties.getError());
    }

    /**
     * 覆盖默认的HTML响应
     *
     * @param request HttpServletRequest
     * @return ModelAndView
     */
    @Override
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        return super.errorHtml(request, response);
    }

    /**
     * 覆盖默认的Json响应
     *
     * @param request HttpServletRequest
     * @return ResponseEntity
     */
    @Override
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Map<String, Object> errorAttributes = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL));
        // 错误状态
        HttpStatus status = getStatus(request);
        log.error("{}", errorAttributes);
        // 输出自定义的Json格式
        Map<String, Object> result = new HashMap<>();
        result.put("code", status.value());
        result.put("message", errorAttributes.get("message"));
        return new ResponseEntity<>(result, HttpStatus.OK);
    }
}